package net;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Vector;

import logic.Manager;
import main.GameDef;

public class UserServer implements GameDef{
	ServerSocket server = null;
	int connections = 0;
	public Manager gameManager;
	public Vector <GameServer>users;
	
	public UserServer(int cantPlayers){
		users = new Vector <GameServer>(0);
		initServer();
		gameManager = new Manager(cantPlayers, this);
	    while(connections < cantPlayers){
	    	waitConnections();
	    }
	}
	
	public void initServer(){
		try{
			server = new ServerSocket(9999);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void waitConnections(){
		try {
			users.add(new GameServer(this, server.accept(), connections));
			connections++;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void serverMessage(Message msg){
		for(int i = 0; i < users.size(); i++){
			users.get(i).sendMessage(msg);
		}
	}

	public void endServer() {
		try {
			for(int i = 0; i < users.size(); i++){
				users.get(i).socket.close();
				users.get(i).socket = null;
				users.get(i).serverThread.interrupt();
			}
			server.close();
			server = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
}
